import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_acrylic/flutter_acrylic.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:system_tray/system_tray.dart';
import 'package:window_example/page_navigation/page_navigation_cubit.dart';
import 'package:window_example/util/platform.dart';
import 'package:window_example/util/window_util.dart';
import 'package:window_example/page_navigation/body_widget.dart';
import 'package:window_example/widget/titlebar_widget.dart';
import 'package:window_manager/window_manager.dart';

import 'drawer/drawer.dart';

var key = GlobalKey();
Color color = Platform.isWindows ? const Color(0xb3ffffff) : Colors.transparent;

class MyScrollBehavior extends MaterialScrollBehavior {
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
      };
}

void main() async {
  if (isDesktop()) {
    WidgetsFlutterBinding.ensureInitialized();
    // Must add this line.
    await windowManager.ensureInitialized();
    await Window.initialize();
    WindowOptions windowOptions = const WindowOptions(
      minimumSize: Size(400, 300),
      // maximumSize: Size(400, 300),
      //window 限制最小尺寸
      size: Size(800, 500),
      //
      center: true,
      // backgroundColor: Colors.transparent,
      // window 背景颜色，默认设置为透明就好
      skipTaskbar: false,
      //true 表示在状态栏不显示该应用
      alwaysOnTop: false,
      //true 表示设置Window一直位于最顶层
      titleBarStyle: TitleBarStyle.hidden,
      ////hidden 表示隐藏TitleBar（缩放、关闭）
      title: "WindowSettingTest",
      //设置窗口的标题，
      windowButtonVisibility: false, //隐藏
    );

    // doWhenWindowReady(() async {
    //   final win = appWindow;
    //   const initialSize = Size(600, 450);
    //   win.minSize = initialSize;
    //   win.size = initialSize;
    //   win.alignment = Alignment.center;
    //   win.title = "Custom window with Flutter";
    //
    //   InterfaceBrightness brightness =
    //   Platform.isMacOS ? InterfaceBrightness.auto : InterfaceBrightness.dark;
    //   await Window.setEffect(
    //       effect: WindowEffect.acrylic,
    //       color: color,
    //       dark: brightness == InterfaceBrightness.dark);
    //   if (Platform.isMacOS) {
    //     if (brightness != InterfaceBrightness.auto) {
    //       Window.overrideMacOSBrightness(
    //         dark: brightness == InterfaceBrightness.dark,
    //       );
    //     }
    //   }
    //   win.show();
    // });

    windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
      windowManager.setResizable(true); //设置窗口不可缩放
      windowManager.setAspectRatio(1.3); //设置窗口宽高比
      windowManager.setHasShadow(true);
      windowManager.setBrightness(Brightness.dark);
    });
  }
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => PageNavigationCubit(),
      child: MyHomePage(title: "ssss"),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WindowListener {
  var isAutoStart = false;
  Timer? _timer;
  bool _toogleTrayIcon = true;
  final SystemTray _systemTray = SystemTray();

  @override
  void initState() {
    super.initState();
    if (isDesktop()) {
      windowManager.addListener(this);
      _initSystemTray();
      windowManager.setPreventClose(false);
    }
  }

  Future<void> _initSystemTray() async {
    //设置系统托盘的图标，必须是.ico后缀的图片
    await _systemTray.initSystemTray(
      iconPath: Platform.isWindows
          ? 'assets/images/tray_icon_original.ico'
          : 'assets/images/img_1.png',
    );
    //设置系统托盘的标题
    _systemTray.setTitle("system tray");
    //设置系统托盘的提示
    _systemTray.setToolTip("How to use system tray with Flutter");
    //注册系统托盘事件
    _systemTray.registerSystemTrayEventHandler((eventName) {
      debugPrint("eventName: $eventName");
      //注册系统托盘事件：点击事件
      if (eventName == kSystemTrayEventClick) {
        //Windows系统：显示主窗口   其他系统弹出托盘菜单弹框
        Platform.isWindows
            ? windowManager.show()
            : _systemTray.popUpContextMenu();
        //注册系统托盘事件：鼠键右键
      } else if (eventName == kSystemTrayEventRightClick) {
        //Windows系统：弹出托盘菜单弹框  其他系统： 显示主窗口
        Platform.isWindows
            ? _systemTray.popUpContextMenu()
            : windowManager.show();
      }
    });
    //创建托盘的菜单
    final Menu _menuMain = Menu();
    await _menuMain.buildFrom([
      //创建子菜单
      SubMenu(
          label: "窗口设置",
          //创建为菜单子项添加图标，格式必须是bmp
          image: Platform.isWindows
              ? 'assets/images/app_icon.bmp'
              : 'assets/images/img_1.png',
          children: [
            //创建可选框类型的菜单项
            MenuItemCheckbox(
                label: "毛玻璃效果",
                checked: true,
                name: 'acrylic_cb',
                onClicked: (MenuItemBase menuItem) async {
                  //更新MenuItemCheckbox的状态
                  await menuItem.setCheck(!menuItem.checked);
                  if (kDebugMode) {
                    print("毛玻璃效果 onClick ${menuItem.checked}");
                  }
                  if (menuItem.checked == true) {
                    showAcrylic(color);
                  } else {
                    closeAcrylic();
                  }
                }),
            MenuItemCheckbox(
                label: "窗口置顶",
                checked: true,
                onClicked: (MenuItemBase menuItem) async {
                  await menuItem.setCheck(!menuItem.checked);
                  if (kDebugMode) {
                    print("窗口置顶 onClick ${menuItem.checked}");
                  }
                  if (menuItem.checked == true) {
                    windowManager.setAlwaysOnTop(true);
                  } else {
                    windowManager.setAlwaysOnTop(false);
                  }
                }),
            MenuItemCheckbox(
                label: "自启动",
                checked: true,
                name: 'auto_start_cb',
                onClicked: (MenuItemBase menuItem) async {
                  // menuItem.checked = !(menuItem.checked == true);
                  await menuItem.setCheck(!menuItem.checked);
                  if (kDebugMode) {
                    print("自启动 onClick ${menuItem.checked}");
                  }
                }),
            MenuItemCheckbox(
                label: "图标闪烁",
                checked: false,
                name: "flash_cb",
                onClicked: (MenuItemBase menuItem) async {
                  MenuItemCheckbox? flashCb =
                      _menuMain.findItemByName<MenuItemCheckbox>("flash_cb");
                  await flashCb?.setCheck(!menuItem.checked);
                  if (kDebugMode) {
                    print("图标闪烁 onClick ${menuItem.checked}");
                  }
                  if (menuItem.checked) {
                    startFlashIcon();
                  } else {
                    stopFlashIcon();
                  }
                }),
          ]),
      //菜单分割线
      MenuSeparator(),
      //菜单项
      MenuItemLabel(
          label: 'Open App',
          image: Platform.isWindows
              ? 'assets/images/app_icon.bmp'
              : 'assets/images/img_1.png',
          onClicked: (MenuItemBase menuItem) {
            windowManager.show();
          }),
      MenuItemLabel(
          label: 'Exit App',
          image: Platform.isWindows
              ? 'assets/images/app_icon.bmp'
              : 'assets/images/img_1.png',
          onClicked: (MenuItemBase menuItem) {
            windowManager.close();
          }),
    ]);
    if (kDebugMode) {
      print("menu:${_menuMain.toString()}");
    }
    //为系统托盘设置菜单项
    await _systemTray.setContextMenu(_menuMain);
    showAcrylic(color);
    setState(() {});
  }

  //开始图标闪烁
  void startFlashIcon() {
    if (kDebugMode) {
      print("startFlashIcon");
    }
    var imageList = const [
      "assets/images/tray_icon_original.ico",
      "assets/images/tray_icon.ico"
    ];
    var index = 0;
    _timer =
        Timer.periodic(const Duration(milliseconds: 500), (Timer timer) async {
      if (kDebugMode) {
        print("path:${imageList[index]}");
      }
      await _systemTray.setImage(imageList[index]);
      index = (index == 0) ? 1 : 0;
    });
  }

  //停止图标闪烁
  void stopFlashIcon() async {
    if (kDebugMode) {
      print("stopFlashIcon");
    }
    _timer?.cancel();
    _timer = null;
    await _systemTray.setImage("assets/images/tray_icon_original.ico");
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  @override
  void onWindowEvent(String eventName) {
    print("event:$eventName");
    super.onWindowEvent(eventName);
  }

  @override
  void onWindowBlur() {
    print("onWindowBlur");
    super.onWindowBlur();
  }

  @override
  void onWindowClose() async {
    var isPreventClose = await windowManager.isPreventClose();
    if (!context.mounted) return;
    if (isPreventClose) {
      print("custom close  action");
      showDialog(
          context: context,
          builder: (_) {
            return AlertDialog(
              title: const Text("提示"),
              actions: [
                TextButton.icon(
                    onPressed: () {
                      Navigator.of(context).pop();
                      windowManager.destroy();
                    },
                    icon: const Icon(Icons.close),
                    label: const Text("确认")),
                TextButton.icon(
                    onPressed: () {
                      print("取消");
                      Navigator.of(context).pop();
                      var height = MediaQuery.of(context).size.height;
                      var width = MediaQuery.of(context).size.width;
                      print("size:${MediaQuery.of(context).size}");
                      print("size:${window.physicalSize}");
                      print("size:${MediaQuery.of(context).devicePixelRatio}");
                      print(
                          "size:height${MediaQuery.of(context).devicePixelRatio * height},width:${MediaQuery.of(context).devicePixelRatio * width}");
                    },
                    icon: const Icon(Icons.remove),
                    label: const Text("取消")),
              ],
            );
          });
    } else {
      print("use system close action");
    }
    print("onWindowClose");
    super.onWindowClose();
  }

  @override
  void onWindowDocked() {
    print("onWindowDocked");
    super.onWindowDocked();
  }

  @override
  void onWindowEnterFullScreen() {
    print("onWindowEnterFullScreen");
    super.onWindowEnterFullScreen();
  }

  @override
  void onWindowFocus() {
    // TODO: implement onWindowFocus
    super.onWindowFocus();
    print("onWindowEnterFullScreen");
    setState(() {});
  }

  @override
  void onWindowLeaveFullScreen() {
    // TODO: implement onWindowLeaveFullScreen
    super.onWindowLeaveFullScreen();
    print("onWindowLeaveFullScreen");
  }

  @override
  void onWindowMaximize() {
    // TODO: implement onWindowMaximize
    super.onWindowMaximize();
    print("onWindowMaximize");
  }

  @override
  void onWindowMinimize() {
    // TODO: implement onWindowMinimize
    super.onWindowMinimize();
    print("onWindowMinimize");
  }

  @override
  void onWindowMove() {
    // TODO: implement onWindowMove
    super.onWindowMove();
    print("onWindowMove");
  }

  @override
  void onWindowMoved() {
    // TODO: implement onWindowMoved
    super.onWindowMoved();
    print("onWindowMove");
  }

  @override
  void onWindowResize() {
    // TODO: implement onWindowResize
    super.onWindowResize();
    print("onWindowResize");
  }

  @override
  void onWindowResized() {
    // TODO: implement onWindowResized
    super.onWindowResized();
    print("onWindowResized");
  }

  @override
  void onWindowRestore() {
    // TODO: implement onWindowRestore
    super.onWindowRestore();
    print("onWindowRestore");
  }

  @override
  void onWindowUndocked() {
    // TODO: implement onWindowUndocked
    super.onWindowUndocked();
    print("onWindowUndocked");
  }

  @override
  void onWindowUnmaximize() {
    // TODO: implement onWindowUnmaximize
    super.onWindowUnmaximize();
    print("onWindowUnmaximize");
  }

  @override
  void onTrayIconMouseDown() {
    windowManager.show();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      scrollBehavior: MyScrollBehavior(),
      home: Scaffold(
        backgroundColor:  isDesktop()?Colors.transparent:Colors.white,
        appBar: isMobile()
            ? AppBar(
                title: const Text("Demo"),
              )
            : null,
        drawer: DrawLayout(),
        body: Container(
          child: Column(mainAxisSize: MainAxisSize.max, children: [
            if (isDesktop()) const TitleBarWidget(),
            const Expanded(child: WindowBodyWidget()),
          ]),
        ),
      ),
      // ),
    );
  }
}
